#!/usr/bin/env python
# coding: utf-8

import logging
from .tnxxx_portimpbase import *
    
support_port_dic = {
    CLI_PORT    : [tnxxx_port_cli, 'root', 'root'],
    BCM_PORT    : [tnxxx_port_bcm, 'weihu', 'cjhyy300'],
    MTN_PORT    : [tnxxx_port_mtn, 'login 1,1', ''],
    DEV_PORT    : [tnxxx_port_dev, 'weihu', 'cjhyy300'],
    ZEBOS_PORT  : [tnxxx_port_zebos, 'zebos', 'en'],
}

class tnxxx_port(object):
    def __init__(self):
        self.__port_obj = None
        self.__ip = "127.0.0.1"
        self.__slot = 0
        self.__port = 0
        logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s %(levelname)-8s %(name)-16s : %(message)s',
                        # filemode='w')
                        )
        self.logger = logging.getLogger(self.__class__.__name__)

    def connect(self, ip, slot, port,usr=None, pwd=None, timeout=30):
        if type(ip)!=str or type(slot)!=int or type(port)!=int:
            print ('Error : param type')
            return False
        # if not support_port_dic.has_key(port):
        if port not in support_port_dic:
            print ('Error : not support_port_dic.has_key(port)')
            return False        
        if self.__ip==ip and self.__slot==slot and self.__port==port and self.check_connect():
            return True
        self.disconnect()
        self.__port_obj = support_port_dic[port][0]()      
        if self.__port_obj == None:
            print ('Error : self.__port_obj == None')
            return False
        self.__ip = ip
        self.__slot = slot
        self.__port = port
        if usr==None or type(usr)!=str:
            usr =  support_port_dic[port][1]
        if pwd==None or type(pwd)!=str:
            pwd =  support_port_dic[port][2]
        rtn = self.__port_obj.connect(ip, slot, port, usr, pwd, timeout)
        
        # print ('connect ip %s, slot %d, port %d : '%(ip, slot, port) + ('successed' if rtn else 'failed'))
        self.logger.info('connect ip %s, slot %d, port %d : '%(ip, slot, port) + ('successed' if rtn else 'failed'))        
        return rtn

    def disconnect(self):
        if self.__port_obj != None:
            self.__port_obj.disconnect()
            self.__port_obj = None
            self.logger.info('disconnect ip %s, slot %d, port %d'%(self.__ip, self.__slot, self.__port))
        return True
                
    def check_connect(self):
        if self.send('', 3, False) == '':
            return False
        return True        

    def send(self, cmd, timeout=50, do_connect = True):
        if type(cmd)!=str or type(timeout)!=int:
            print ('Error : param type wrong')
            return ''
        rtn_all = ''
        times = 0
        while times < 1:
            rtn_all += self.__port_obj.send(cmd, timeout)            
            
            if rtn_all.find(self.__port_obj.get_prompt()) >= 0:  
                break
            if do_connect == True:
                self.connect(self.__ip, self.__slot, self.__port)
            times += 1      
        # self.logger.info(rtn_all)
        return rtn_all
        
    def send_only(self, cmd, timeout=50, do_connect = True):
        if type(cmd)!=str or type(timeout)!=int:
            print ('Error : param type wrong')
            return False
        rtn_all = ''
        rtn_flag = False
        times = 0
        while times < 1:
            rtn_flag,rtn_str = self.__port_obj.send_only(cmd, timeout)
            rtn_all += rtn_str
            
            print(rtn_all)
            if rtn_flag:
                break
            if do_connect == True:
                self.connect(self.__ip, self.__slot, self.__port)
            times += 1   
        self.logger.info(rtn_all)
        return rtn_flag
       
    def check_default_rtn(self, cmd, rtn_str):
        if self.__port_obj!=None:
            return self.__port_obj.check_default_rtn(cmd, rtn_str)
        return False

if __name__ == '__main__':
    case = tnxxx_port()
    print (case.connect("10.15.1.8",3,23))
    print (1)
    """
    case.connect('127.0.0.1', 6000)
    case.send('c t')
    case.send('show interface',1,False)
    case.send('show ipaddr')
    case.send_only('show interface')
    case.send_only('show interface')
    case.send_only('show interface')
    case.send_only('show interface')
    case.send_only('show interface')
    case.send('show ipaddr')
    case.disconnect()

    case.connect('192.168.210.179', 6000)
    case.send('c t')
    case.send('show interface')
    case.disconnect()
    
    case.connect('192.168.210.179', 23)
    case.send('dbg_if_print')
    case.send('i')
    case.disconnect()
    
    case.connect('192.168.210.179', 9999)
    case.send('ps')
    case.send('show c')
    case.disconnect()
     
    print(case.connect('192.168.210.168', 3333))
    print(case.send('$.nsp.log.0.show_rmem_logs "qoss",1,100'))
    print(case.disconnect())
    """  
    print ("-"*30,"The END","-"*30)
